package com.hu.user.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.hu.common.pojo.User;
import com.hu.user.service.IUserService;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ServerWebExchange;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Component
public class TokenUtils {
    private static IUserService staticUserService;
    // 注入userService
    @Resource
    private IUserService userService;

    // 当依赖(userService)注入完成后用于执行一些初始化操作
    @PostConstruct
    public void setUserService() {
        // getCurrentUser声明为static方法，如果直接调用userService会报错，这里需要先拿到userService把它付给一个静态属性
        staticUserService = userService;
    }

    /**
     * 生成token
     *
     * @return
     */
    public static String genToken(String userId, String sign) {
        return JWT.create().withAudience(userId) // 将 user id 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }


    /**
     * 获取当前登录的用户信息
     *
     * @return user对象
     * 写成静态方法，不用new就可以在项目的任何地方去调用它了，
     * 实例：controller层的findPage方法
     */
    public static User getCurrentUser(String token) {
        try {
            if (StrUtil.isNotBlank(token)) {
                System.out.println("token+++++++++++++>" + token);
                String userId = JWT.decode(token).getAudience().get(0);
                System.out.println("userId+++++++++++++>" + userId);
                System.out.println("u+++++++++++++>" + staticUserService.getById(Integer.valueOf(userId)));
                return staticUserService.getById(Integer.valueOf(userId));
            }

        } catch (Exception e) {
            return null;
        }
        return null;
    }
}
